/*
 * @Author: Wangjun
 * @Date: 2022-05-20 14:10:33
 * @LastEditTime: 2024-12-28 15:27:16
 * @LastEditors: wangjun haodreams@163.com
 * @Description:字段名转ids，方便查找
 * @FilePath: \libs\easy\nametoids.go
 * hnxr
 */
package easy

import (
	"reflect"
	"strings"
)

/**
 * @description: struct 字段名转为ids
 * @param {string} prefix
 * @param {map[string][]int} key
 * @param {[]int} paths
 * @param {reflect.Type} t
 * @param {bool} toLower 是否转为小写
 * @return {*}
 */
func MapNameID(prefix string, mapKeyId map[string][]int, paths []int, t reflect.Type, toLower bool, keys ...*[]string) {
	var names *[]string
	var srcNames *[]string
	var shortName *[]string
	if len(keys) > 0 {
		names = keys[0]
	}
	if len(keys) > 1 {
		srcNames = keys[1]
	}
	if len(keys) > 2 {
		shortName = keys[2]
	}

	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	//log.Println(prefix + t.String())
	for i := 0; i < t.NumField(); i++ {
		newPaths := make([]int, len(paths))
		copy(newPaths, paths)
		newPaths = append(newPaths, i)
		fieldType := t.Field(i)

		typ := fieldType.Type

		if typ.Kind() == reflect.Ptr {
			typ = typ.Elem()
		}

		//log.Println(prefix+fieldType.Name, typ.Kind())

		if fieldType.Anonymous {
			if typ.Kind() == reflect.Struct {
				MapNameID(prefix, mapKeyId, newPaths, typ, toLower, names, srcNames, shortName)
			} else {
				name := prefix + fieldType.Name
				if srcNames != nil {
					*srcNames = append(*srcNames, name)
				}
				if shortName != nil {
					*shortName = append(*shortName, fieldType.Name)
				}
				if toLower {
					name = strings.ToLower(name)
				}
				mapKeyId[name] = newPaths
				if names != nil {
					*names = append(*names, name)
				}

			}
			continue
		}
		if typ.Kind() == reflect.Struct {
			tag := fieldType.Tag.Get("json")
			if tag == "-" {
				continue
			}
			if fieldType.IsExported() {
				MapNameID(prefix+fieldType.Name+".", mapKeyId, newPaths, typ, toLower, names)
			}
			continue
		}

		if fieldType.IsExported() {
			name := prefix + fieldType.Name
			if srcNames != nil {
				*srcNames = append(*srcNames, name)
			}
			if shortName != nil {
				*shortName = append(*shortName, fieldType.Name)
			}

			if toLower {
				name = strings.ToLower(name)
			}
			mapKeyId[name] = newPaths
			if names != nil {
				*names = append(*names, name)
			}
		}
	}
}
